#include "ChartWidget.h"

#include <models/robotlist.h>

#include <mainwindow.h>

ChartWidget::ChartWidget(QWidget *parent)
    : QWidget(parent)
{

}

void ChartWidget::setupUI()
{
    // 创建主布局
    mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    
    // 创建复选框容器
    checkBoxContainer = new QWidget;
    checkBoxContainer->setMinimumHeight(20*g_xScale);
    checkBoxContainer->setMaximumHeight(40*g_xScale);
    checkBoxContainer->setStyleSheet("background-color: #48494E;");
    
    // 创建复选框布局
    checkBoxLayout = new QHBoxLayout(checkBoxContainer);
    checkBoxLayout->setContentsMargins(21*g_xScale, 0, 21*g_xScale, 0);

    // 创建图表布局
    chartsLayout = new QHBoxLayout;
    chartsLayout->setSpacing(0);
    chartsLayout->setContentsMargins(0, 0, 0, 0);
    
    // 创建图表容器
    chart1Widget = new QWidget;
    chart2Widget = new QWidget;
    chart3Widget = new QWidget;
    
    // 添加到图表布局
    chartsLayout->addWidget(chart1Widget);
    chartsLayout->addWidget(chart2Widget);
    chartsLayout->addWidget(chart3Widget);
    
    // 添加到主布局
    mainLayout->addWidget(checkBoxContainer);
    mainLayout->addLayout(chartsLayout);
    // 设置默认大小
    // resize(1200, 400);
    // 创建三个图表实例
    chart1 = new YSChartView();
    chart2 = new YSChartView();
    chart3 = new YSChartView();
    // 设置每个图表的基准大小
    chart1->setBaseSize(width()/3,height()-checkBoxContainer->height());
    chart2->setBaseSize(width()/3,height()-checkBoxContainer->height());
    chart3->setBaseSize(width()/3,height()-checkBoxContainer->height());

    // 设置图表标题
    chart1->setChartTitle("位姿");
    chart2->setChartTitle("速度");
    chart3->setChartTitle("力矩");

    // 设置图例位置到底部
    chart1->setLegendVisible(false);
    chart2->setLegendVisible(false);
    chart3->setLegendVisible(false);

    // 为每个图表容器创建垂直布局
    QVBoxLayout* layout1 = new QVBoxLayout(chart1Widget);
    QVBoxLayout* layout2 = new QVBoxLayout(chart2Widget);
    QVBoxLayout* layout3 = new QVBoxLayout(chart3Widget);

    // 设置布局边距
    layout1->setContentsMargins(0, 0, 0, 0);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout3->setContentsMargins(0, 0, 0, 0);

    // 将图表添加到布局中
    layout1->addWidget(chart1);
    layout2->addWidget(chart2);
    layout3->addWidget(chart3);

}

void ChartWidget::setupCharts(JointType jointType)
{
    curJointType=jointType;
    // 清除现有的复选框
    for(YSCheckBox* checkbox : checkBoxes) {
        checkbox->deleteLater();
    }
    checkBoxes.clear();

    while (checkBoxLayout->count() > 0) {
        QLayoutItem* item = checkBoxLayout->takeAt(0);
        if (item->widget()) {
            delete item->widget();
        }
        delete item;
    }

    QVector<JOINT> strVName = getJointByType(jointType);

    // 创建折线配置
    QVector<LineConfig> configs;
    QVector<QColor> colors{QColor(0,255,0),QColor(255,255,0),QColor(255,250,240),QColor(0,0,255),QColor(255,20,147),QColor(0,191,255),QColor(255,140,0),QColor(0,255,255)};  // 保存颜色以供复选框使用

    // 设置需要的折线数量（可以根据需求修改）
    for(int i = 0; i < strVName.length(); i++) {
        // 生成随机HSV颜色，保证颜色饱和度和亮度适中
        int index = i>=colors.length()?colors.length()-1:i;
        configs.append(LineConfig(
            strVName[i].strName,
            colors[index],
            true
            ));
        // 创建新的复选框

        YSCheckBox* checkbox = new YSCheckBox(colors[index],strVName[i].strName);
        checkbox->setChecked(true);
        checkbox->setFixedSize(150*g_xScale,40 * g_yScale);
        // QFont font;
        // // 设置字体名称为微软雅黑
        // font.setFamily("Microsoft YaHei");
        // // 设置字号为 14 号
        // font.setPointSize(14);
        // checkbox->setFont(font);
        // checkbox->setChecked(true);
        // QColor color = colors[i];
        // QString styleSheet = QString(
        //                          "YSCheckBox{ \
        //                              color: %1;}"
        //                          ).arg(color.name());
        //   checkbox->setStyleSheet(styleSheet);

        checkBoxes.append(checkbox);
        checkBoxLayout->addWidget(checkbox);
    }
    checkBoxLayout->addStretch();
    checkBoxLayout->setSpacing(10*g_xScale);

    // 初始化折线
    chart1->initializeLines(configs);
    chart2->initializeLines(configs);
    chart3->initializeLines(configs);

    chart1->setRange(-10,10);
    chart2->setRange(0,1);
    chart3->setRange(0,1);
    setupConnections();
}

void ChartWidget::setupCheckBoxes(int count)
{
    Q_UNUSED(count);
}

void ChartWidget::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
        connect(pCurRobot,&Robot::sportStateChanged, this, &ChartWidget::updateData,Qt::UniqueConnection);

    if(m_bFirst)
    {
        m_bFirst=false;
        // 计算新的按钮大小
        int newHeight = static_cast<int>(height() * g_xScale);
        setFixedHeight(newHeight);
        setupUI();
    }
}

void ChartWidget::setupConnections()
{
    // 连接所有复选框的信号
    for(int i = 0; i < checkBoxes.size(); i++) {
        connect(checkBoxes[i], &YSCheckBox::stateChanged, this, &ChartWidget::onCheckBoxStateChanged,Qt::UniqueConnection);
    }
}

void ChartWidget::onCheckBoxStateChanged(int state)
{
    YSCheckBox* checkbox = qobject_cast<YSCheckBox*>(sender());
    if (!checkbox) return;
    
    int index = checkBoxes.indexOf(checkbox);
    if (index >= 0) {
        bool visible = (state == Qt::Checked);
        chart1->setLineVisible(index, visible);
        chart2->setLineVisible(index, visible);
        chart3->setLineVisible(index, visible);
    }
}

void ChartWidget::updateData()
{
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();

    if(pCurRobot)
    {
        SportState SportState;
        QVector<float> jointAngles;
        QVector<float> jointSpeed;
        QVector<float> jointMoment;
        QVector<JOINT> joints= getJointByType(curJointType);
        switch (curJointType){
        case LEFT_TIP_JOINT:
        case RIGHT_TIP_JOINT:
            break;
        case LEFT_TOOL_HAND_JOINT:
        case LEFT_TOOL_GRIPPER_JOINT:
        case LEFT_TOOL_SUCKER_JOINT:
        {
            QVector<float> realArcs = pCurRobot->leftFingerArc();
            QVector<float> realSpeeds = pCurRobot->leftFingerSpeed();
            QVector<float> realMoments = pCurRobot->leftFingerMoment();
            for(int i=0;i<joints.size();i++)
            {
                jointAngles.push_back(realArcs[joints[i].nIndex]*180/M_PI);
                jointSpeed.push_back(realSpeeds[joints[i].nIndex]);
                jointMoment.push_back(realMoments[joints[i].nIndex]);
            }
        }
        break;
        case RIGHT_TOOL_HAND_JOINT:
        case RIGHT_TOOL_GRIPPER_JOINT:
        case RIGHT_TOOL_SUCKER_JOINT:
        {
            QVector<float> realArcs = pCurRobot->rightFingerArc();
            QVector<float> realSpeeds = pCurRobot->rightFingerSpeed();
            QVector<float> realMoments = pCurRobot->rightFingerMoment();
            for(int i=0;i<joints.size();i++)
            {
                jointAngles.push_back(realArcs[joints[i].nIndex]*180/M_PI);
                jointSpeed.push_back(realSpeeds[joints[i].nIndex]);
                jointMoment.push_back(realMoments[joints[i].nIndex]);
            }
        }
        break;
        default:
        {
            SportState=pCurRobot->SportStateData();
            float * realArcs=SportState.realArc;
            float * realSpeeds=SportState.realSpeed;
            float * realMoments=SportState.realMoment;
            for(int i=0;i<joints.size();i++)
            {
                jointAngles.push_back(realArcs[joints[i].nIndex]*180/M_PI);
                jointSpeed.push_back(realSpeeds[joints[i].nIndex]);
                jointMoment.push_back(realMoments[joints[i].nIndex]);
            }
        }
            break;
        }

        float fMin = chart1->getMinRange();
        float fMax = chart1->getMaxRange();
        for(int i = 0; i < jointAngles.size(); ++i)
        {
            if(jointAngles[i] < fMin)
                fMin = std::floor(jointAngles[i]/10)*10;
            if(jointAngles[i] > fMax)
                fMax = std::ceil(jointAngles[i]/10) * 10;
        }
        chart1->setRange(fMin,fMax);
        chart1->updateAllLines(jointAngles);


        fMin = chart2->getMinRange();
        fMax = chart2->getMaxRange();
        for(int i = 0; i < jointSpeed.size(); ++i)
        {
            if(jointSpeed[i] < fMin)
                fMin = std::floor(jointSpeed[i]/10)*10;
            if(jointSpeed[i] > fMax)
                fMax = std::ceil(jointSpeed[i]/10) * 10;
        }
        chart2->setRange(fMin,fMax);
        chart2->updateAllLines(jointSpeed);


        fMin = chart3->getMinRange();
        fMax = chart3->getMaxRange();
        for(int i = 0; i < jointMoment.size(); ++i)
        {
            if(jointMoment[i] < fMin)
                fMin = std::floor(jointMoment[i]/10)*10;
            if(jointMoment[i] > fMax)
                fMax = std::ceil(jointMoment[i]/10) * 10;
        }
        chart3->setRange(fMin,fMax);
        chart3->updateAllLines(jointMoment);
    }
}

ChartWidget::~ChartWidget()
{
}

